<?php

namespace Yj\Excel;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Yj\Excel\Concerns\WithProperties;
use Yj\Excel\Factories\WriterFactory;

class Write
{
    public function export($export,string $writerType){
        $this->open($export);
        $this->write($writerType);
    }
    /**
     * @param object $export
     *
     * @return $this
     */
    public function open($export)
    {
        $this->exportable  = $export;
        $this->spreadsheet = new Spreadsheet();
        $this->spreadsheet->disconnectWorksheets();
        $this->handleDocumentProperties($export);
        return $this;
    }

    public function write($writerType){
        $this->spreadsheet->setActiveSheetIndex(0);
        $writer = WriterFactory::make(
            $writerType,
            $this->spreadsheet,
            $this->exportable
        );
        $writer->save('a.xlsx');
    }

    /**
     * @param object $export
     */
    protected function handleDocumentProperties($export)
    {
        if ($export instanceof WithProperties) {

            $properties = array_merge([], $export->properties());
        }

        $props = $this->spreadsheet->getProperties();
        foreach (array_filter($properties) as $property => $value) {
            switch ($property) {
                case 'title':
                    $props->setTitle($value);
                    break;
                case 'description':
                    $props->setDescription($value);
                    break;
                case 'creator':
                    $props->setCreator($value);
                    break;
                case 'lastModifiedBy':
                    $props->setLastModifiedBy($value);
                    break;
                case 'subject':
                    $props->setSubject($value);
                    break;
                case 'keywords':
                    $props->setKeywords($value);
                    break;
                case 'category':
                    $props->setCategory($value);
                    break;
                case 'manager':
                    $props->setManager($value);
                    break;
                case 'company':
                    $props->setCompany($value);
                    break;
            }
        }
    }
}